<%@ page language="java" pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>购物车</title>
    <link rel="stylesheet" type="text/css" href="/css/index.css"/>
    <script type="text/javascript" src="/js/jquery-3.7.1.min.js"></script>
    <style>
        /* 购物车样式 */
        .cart-container {
            width: 100%;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 30px;
        }

        .cart-title {
            font-size: 24px;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .cart-header {
            display: flex;
            background-color: #f8f8f8;
            padding: 12px 0;
            border-radius: 4px;
            font-weight: bold;
            color: #333;
        }

        .cart-item {
            display: flex;
            padding: 20px 0;
            border-bottom: 1px solid #eee;
            align-items: center;
        }

        .cart-col {
            padding: 0 10px;
            text-align: center;
        }

        .product-info {
            flex: 3;
            display: flex;
            align-items: center;
            text-align: left;
        }

        .product-img {
            width: 80px;
            height: 80px;
            object-fit: cover;
            margin-right: 15px;
            border-radius: 4px;
        }

        .product-name {
            font-size: 16px;
            color: #333;
        }

        .product-price {
            flex: 1;
            color: #e4393c;
            font-weight: bold;
        }

        .product-quantity {
            flex: 1;
        }

        .quantity-control {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 120px;
            margin: 0 auto;
        }

        .quantity-btn {
            width: 30px;
            height: 30px;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            font-size: 16px;
            cursor: pointer;
        }

        .quantity-input {
            width: 50px;
            height: 30px;
            text-align: center;
            border: 1px solid #ddd;
            margin: 0 5px;
        }

        .product-total {
            flex: 1;
            color: #e4393c;
            font-weight: bold;
        }

        .product-action {
            flex: 1;
        }

        .delete-btn {
            padding: 5px 10px;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            color: #666;
        }

        .delete-btn:hover {
            background-color: #e4393c;
            color: #fff;
            border-color: #e4393c;
        }

        .cart-summary {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        .cart-total {
            margin-right: 20px;
            font-size: 18px;
        }

        .total-price {
            color: #e4393c;
            font-weight: bold;
            font-size: 24px;
        }

        .checkout-btn {
            padding: 10px 30px;
            background-color: #e4393c;
            color: #fff;
            border: none;
            border-radius: 4px;
            font-size: 18px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .checkout-btn:hover {
            background-color: #c1272d;
        }
    </style>
    <script type="text/javascript">
        //用于用户中心左边菜单栏的选择项的样式
        function setSelectedClass(url) {
            $('div.cont ul.list li a[href~="' + url + '"]').parent().addClass("current");
        }

        $(function () {
            $('.mycart').hover(
                function () {
                    $('#div_mycart').show('slow');
                },
                function () {
                    $('#div_mycart').hide('slow');
                }
            );
        });
        $(function () {
            $('.allsort').hover(function () {
                $('#div_allsort').show();
            }, function () {
                $('#div_allsort').hide();
            });
        });


    </script>
</head>
<body class="index">
<div class="container">
    <div class="header">
        <h1 class="logo">
            <a title="" style="background:url(images/logo.png);" href="/">电子商务平台</a>
        </h1>
        <ul class="shortcut">
            <li class="first"><a href="ucenter">我的账户</a></li>
            <li><a href="order/user">我的订单</a></li>
            <li class='last'><a href="">使用帮助</a></li>
        </ul>
        <p class="loginfo">
            <c:if test="${not empty sessionScope.user}">
                ${user.account}您好，欢迎您来到${site}购物！[<a href="/logout" class="reg">安全退出</a>]
            </c:if>
            <c:if test="${empty sessionScope.user}">
                [<a href="/login">登录</a>
                <a class="reg" href="/register">免费注册</a>]
            </c:if>
        </p>
    </div>
    <div class="navbar">
        <ul>
            <li><a href="/">首页</a></li>
        </ul>

    </div>
    <div class="searchbar">
        <div class="allsort">
            <a href="javascript:void(0);">全部商品分类</a>

            <!--总的商品分类-开始-->
            <ul class="sortlist" id='div_allsort' style='display:none'>

                <c:forEach items="${categories}" var="category">
                    <li>
                        <h2>
                            <a href="/?categoryId=${category.id}">${category.name}</a>
                        </h2>
                    </li>
                </c:forEach>
            </ul>
        </div>

        <div class="searchbox">
            <form method='get' action=''>
                <input type='hidden' name='controller' value='site'/> <input
                    type='hidden' name='action' value='search_list'/> <input
                    class="text" type="text" name='word' autocomplete="off"
                    value="输入关键字..."/> <input class="btn" type="submit" value="商品搜索"
                                                   onclick="checkInput('word','输入关键字...');"/>
            </form>

        </div>
        <div class="hotwords">热门搜索：</div>
    </div>

    <div class="wrapper clearfix">
        <div class="wrap_box">
            <!-- 购物车商品列表 -->
            <div class="cart-container">


                <div class="cart-header">
                    <div class="cart-col product-info">商品信息</div>
                    <div class="cart-col product-price">单价</div>
                    <div class="cart-col product-quantity">数量</div>
                    <div class="cart-col product-total">小计</div>
                    <div class="cart-col product-action">操作</div>
                </div>

                <div class="cart-items">
                    <!-- 购物车商品项 1 -->
                    <c:forEach items="${cartList}" var="cart" varStatus="status">
                        <c:set var="itemId" value="${cart.id}"/>
                        <div class="cart-item">
                            <div class="cart-col product-info">
                                <img src="${cart.image}" alt="${cart.name}" class="product-img">
                                <div class="product-name">${cart.name}</div>
                            </div>
                            <div class="cart-col product-price">￥${cart.salePrice}</div>
                            <div class="cart-col product-quantity">
                                <div class="quantity-control">
                                    <button class="quantity-btn minus" onclick="updateQuantity(${itemId}, -1)">-
                                    </button>
                                    <input type="number" class="quantity-input" id="quantity-${itemId}"
                                           value="${cart.quantity}" min="1" onchange="updateQuantity(${itemId}, 0)">
                                    <button class="quantity-btn plus" onclick="updateQuantity(${itemId}, 1)">+</button>
                                </div>
                            </div>
                            <div class="cart-col product-total" id="total-${itemId}">
                                ￥${cart.salePrice * cart.quantity}</div>
                            <div class="cart-col product-action">
                                <button class="delete-btn" onclick="removeItem(${itemId})">删除</button>
                            </div>
                        </div>


                        <div class="cart-data" style="display: none;">
                            <div class="goods_id">${cart.goodsId}</div>
                            <div class="create_time">${cart.createTime}</div>
                            <div class="update_time">${cart.updateTime}</div>
                            <div class="image">${cart.image}</div>
                            <div class="name">${cart.name}</div>
                            <div class="sale_price">${cart.salePrice}</div>
                        </div>

                    </c:forEach>
                </div>

                <div class="cart-summary">
                    <div class="cart-total">
                        <span>总计：</span>
                        <span class="total-price" id="cart-total-price">￥99999999</span>
                    </div>
                    <button class="checkout-btn" onclick="checkout()">立即支付</button>
                </div>
            </div>
        </div>
    </div>

    <div class="footer">
        <p class="links">
            <a href="">关于我们</a>|<a href="">常见问题</a>|<a href="">安全交易</a>|<a href="">购买流程</a>|<a
                href="">如何付款</a>|<a href="">联系我们</a>|<a href="">合作提案</a>
        </p>
        Copyright 蜗牛学苑© 2015-2024 <a class="copyys" target="_blank" href="">蜀ICP备01000010号</a>
    </div>
</div>
</body>
<script>
    // 购物车功能
    // 更新商品数量
    function updateQuantity(itemId, change) {
        const quantityInput = document.getElementById(`quantity-` + itemId);
        let newQuantity = parseInt(quantityInput.value);

        if (change !== 0) {
            newQuantity += change;
        } else {
            newQuantity = parseInt(quantityInput.value);
        }

        // 确保数量至少为1
        if (newQuantity < 1) {
            newQuantity = 1;
        }

        quantityInput.value = newQuantity;

        // 更新小计
        updateItemTotal(itemId);

        // 更新购物车总价
        updateCartTotal();
    }

    // 更新单个商品小计
    function updateItemTotal(itemId) {
        var id = "quantity-" + itemId;
        const quantity = parseInt(document.getElementById(id).value);
        const priceText = document.querySelector("#total-" + itemId).previousElementSibling.previousElementSibling.textContent;
        const price = parseFloat(priceText.replace('￥', ''));

        const total = quantity * price;
        document.getElementById(`total-` + itemId).textContent = `￥` + total;
    }

    // 更新购物车总价
    function updateCartTotal() {
        let totalPrice = 0;

        // 获取所有商品小计并求和
        const totalElements = document.querySelectorAll('[id^="total-"]');
        totalElements.forEach(element => {
            const priceText = element.textContent;
            const price = parseFloat(priceText.replace('￥', ''));
            totalPrice += price;
        });

        document.getElementById('cart-total-price').textContent = `￥` + totalPrice;
    }

    // 删除商品
    function removeItem(itemId) {
        $.ajax({
            url: '/cart/delete',
            type: 'POST',
            data: {
                id: itemId
            },
            success: function (response) {
                if (response === "success") {
                    const item = document.querySelector(`#quantity-` + itemId).closest('.cart-item');
                    item.remove();
                    console.log('删除成功');
                    updateCartTotal();
                    alert('删除成功')
                } else {
                    console.log('删除失败');
                    alert('删除失败，请重试');
                }
            },
            error: function (xhr, status, error) {
                console.error('删除失败:', error);
                alert('删除失败，请重试');
            }
        });
    }

    function getCartData() {
        const cartItems = document.querySelectorAll('.cart-item');
        const cartDataList = [];

        cartItems.forEach(item => {
            // 获取当前 cart-item 下的 cart-data
            const dataDiv = item.nextElementSibling;

            if (!dataDiv || !dataDiv.classList.contains('cart-data')) {
                console.warn('找不到 cart-data 元素');
                return;
            }

            const quantityInput = item.querySelector('.quantity-input');
            const itemId = quantityInput.id.split('-')[1]; // cart.id
            const quantity = parseInt(quantityInput.value); // 当前数量

            const goodsId = dataDiv.querySelector('.goods_id').textContent.trim();
            const createTime = dataDiv.querySelector('.create_time').textContent.trim();
            const updateTime = dataDiv.querySelector('.update_time').textContent.trim();
            const image = dataDiv.querySelector('.image').textContent.trim();
            const name = dataDiv.querySelector('.name').textContent.trim();
            const salePriceText = dataDiv.querySelector('.sale_price').textContent.trim();
            const salePrice = parseFloat(salePriceText);

            cartDataList.push({
                id: itemId,
                goodsId: goodsId,
                quantity: quantity,
                createTime: createTime,
                updateTime: updateTime,
                image: image,
                name: name,
                salePrice: salePrice
            });
        });

        return cartDataList;
    }


    // 结算
    function checkout() {

        const cartData = getCartData();
        console.log(cartData);
        $.ajax({
            url: '/cart/update',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(cartData),
            success: function (response) {
                if (response === "success") {
                    alert('购物车保存成功');
                    window.location.href = '/order/add';
                } else if (response === "fail") {
                    console.log('商品库存不足');
                } else {
                    alert(response);
                }
            },
            error: function (xhr, status, error) {
                alert('商品库存不足');
                console.error('商品库存不足:', error);
            }
        });
        // alert('正在跳转到支付页面...');
        // 这里可以添加跳转到支付页面的代码
        // 再次判断所有商品数量是否超过库存

        // window.location.href = '/order/submit';
    }

    // function submit(cartData) {
    //     $.ajax({
    //         // url: '/order/submit',
    //         url: '/cart/submit',
    //         type: 'POST',
    //         contentType: 'application/json',
    //         data: JSON.stringify(cartData),
    //         success: function(response) {
    //             if (response === "success") {
    //                 window.location.href = '/order/submit';
    //             } else {
    //                 alert('提交失败，请重试');
    //             }
    //         },
    //         error: function(xhr, status, error) {
    //             alert('提交失败，请重试');
    //             console.error('提交失败:', error);
    //         }
    //     })
    //
    // }


    window.onload = function () {
        updateCartTotal(); // 页面加载完成后自动执行一次
        // updateItemTotal()
    };
</script>
</html>
